package com.cykj.management.activity

import android.bluetooth.BluetoothAdapter
import android.bluetooth.BluetoothDevice
import android.bluetooth.BluetoothManager
import android.content.*
import android.graphics.Bitmap
import android.os.*
import androidx.localbroadcastmanager.content.LocalBroadcastManager
import com.cykj.management.Constant
import com.cykj.management.common.MyLog
import com.kaer.sdk.IDCardItem
import com.kaer.sdk.bt.BtReadClient
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.plugin.common.BasicMessageChannel
import io.flutter.plugin.common.StandardMessageCodec
import java.io.File
import java.io.FileOutputStream
import java.util.*
import kotlin.concurrent.thread

/**
 *
 */
class MainActivity : BaseActivity() {
    companion object {
        const val MESSAGE_RECEIVE_TAG = 1
        const val BLUETOOTH_SOCKET_NOT_CONNECT = 2
        const val CONNECT_STATE = 3
    }

    private val TAG = "MainActivity"
    private val bluetoothChannelName by lazy { "samples.flutter.io/bluetooth" }
    private var bluetoothPlatform: BasicMessageChannel<Any>? = null

    private var address: String? = null
    override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
        super.configureFlutterEngine(flutterEngine)
        bluetoothPlatform = BasicMessageChannel(flutterEngine.dartExecutor.binaryMessenger, bluetoothChannelName, StandardMessageCodec())
        bluetoothPlatform?.setMessageHandler { message, reply ->
            when (message) {
                "openBluetooth" -> reply.reply(openBluetooth())
                "closeBluetooth" -> reply.reply(closeBluetooth())
                "getBluetoothState" -> reply.reply(getBluetoothState())
                "getLocalDeviceName" -> reply.reply(getLocalDeviceName())
                "getBondedDevices" -> reply.reply(getBondedDevices())
                "receiveMessage" -> {
                    receiveMessage()
                }
                else -> {
                    val map = message as Map<*, *>
                    if ("connectDevice" == map["method"]) {
                        connectDevice(map["data"] as Map<*, String>)
                    }
                }
//                else -> reply.reply("没有匹配到消息")
            }
        }
    }


    override fun onCreate(savedInstanceState: Bundle?, persistentState: PersistableBundle?) {
        super.onCreate(savedInstanceState, persistentState)
        if (bluetoothPlatform == null) {
            bluetoothPlatform = BasicMessageChannel(flutterEngine?.dartExecutor!!.binaryMessenger, bluetoothChannelName, StandardMessageCodec())
        }
        bluetoothPlatform!!.send(mutableMapOf("method" to "onCreate"))

        val intentFilter = IntentFilter()
        intentFilter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED)
        intentFilter.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED)
        intentFilter.addAction(BluetoothDevice.ACTION_ACL_DISCONNECTED)
        intentFilter.addAction(BluetoothDevice.ACTION_ACL_CONNECTED)
        registerReceiver(broadcast, intentFilter)
        LocalBroadcastManager.getInstance(this)
                .registerReceiver(broadcast, intentFilter)


    }

    private val broadcast: BroadcastReceiver = object : BroadcastReceiver() {
        override fun onReceive(context: Context?, intent: Intent?) {
            val action = intent?.action
            if (action != null) {
                when (action) {
                    BluetoothAdapter.ACTION_STATE_CHANGED -> {
                        when (intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, 0)) {
                            BluetoothAdapter.STATE_TURNING_ON -> {//蓝牙正在打开
                                stateTurningOn()
                            }
                            BluetoothAdapter.STATE_TURNING_OFF -> {//蓝牙正在关闭
                                stateTurningOff()
                            }
                            BluetoothAdapter.STATE_ON -> {//蓝牙已经打开
                                stateTurningOn()
                            }
                            BluetoothAdapter.STATE_OFF -> {//蓝牙已经关闭
                                stateTurningOff()
                            }
                        }
                    }
                    else -> bluetoothPlatform?.send(action)
                }
            }
        }
    }

    private fun stateTurningOn() {
        bluetoothPlatform?.send("stateTurningOn")
    }

    private fun stateTurningOff() {
        bluetoothPlatform?.send("stateTurningOff")
    }


    //开启蓝牙
    private fun openBluetooth(): Boolean {
        val adapter = BluetoothAdapter.getDefaultAdapter()
        if (adapter.isEnabled) return true
        adapter.enable()
        return adapter.isEnabled
    }

    //关闭蓝牙
    private fun closeBluetooth(): Boolean {
        val adapter = BluetoothAdapter.getDefaultAdapter()
        if (!adapter.isEnabled) return false
        adapter.disable()
        return adapter.isEnabled
    }

    //获取蓝牙状态
    private fun getBluetoothState(): Int {
        val bluetoothManager = getSystemService(Context.BLUETOOTH_SERVICE) as BluetoothManager

        return bluetoothManager.adapter.state
    }

    //获取本机蓝牙名称
    private fun getLocalDeviceName(): String? {
        val adapter = BluetoothAdapter.getDefaultAdapter()
        if (adapter.isEnabled) {
            return adapter.name
        }
        return "没有获取到设备名称"
    }

    //获取已绑定的蓝牙设备
    private fun getBondedDevices(): ArrayList<Map<String, String>>? {
        val adapter = BluetoothAdapter.getDefaultAdapter()
        if (adapter.isEnabled) {
            val list = arrayListOf<Map<String, String>>()

            val toList = adapter.bondedDevices.toList()
            toList.forEach { device ->
                val map = mutableMapOf<String, String>()
                map["name"] = device.name
                map["address"] = device.address
                list.add(map)
            }
            return list
        }
        return null
    }

    //连接蓝牙设备
    private fun connectDevice(map: Map<*, String>) {
        val t = Runnable {
            run {
                val mClient = BtReadClient.getInstance()
                address = map["address"]
                val connectBt = mClient.connectBt(map["address"])
                val obtainMessage = handler.obtainMessage(CONNECT_STATE, connectBt)
                handler.sendMessage(obtainMessage)
            }
        }
        Thread(t).start()
    }

    //蓝牙读卡器读卡
    private fun receiveMessage() {
        thread {
            val adapter = BluetoothAdapter.getDefaultAdapter()
            val mBtReadClient = BtReadClient.getInstance()
            if (address != null) {
                val remoteDevice = adapter.getRemoteDevice(address)
                if (remoteDevice.name.toUpperCase(Locale.getDefault()).contains("KT8003")) {
                    val result = mBtReadClient.connectServer(context, Constant.url, Constant.acc, Constant.url)
                }
            }


            val idCardItem = mBtReadClient.readCert()
            handler.sendMessage(handler.obtainMessage(MESSAGE_RECEIVE_TAG, idCardItem))
        }

    }


    private fun isConnectedDevice(address: String) {
    }

    private val handler = object : Handler(Looper.getMainLooper()) {
        override fun handleMessage(msg: Message) {
            when (msg.what) {
                MESSAGE_RECEIVE_TAG -> {
                    val idCardItem = msg.obj as IDCardItem

                    var picPath = ""
                    var compress = false
                    if (idCardItem.picBitmap != null) {
                        val pathname = "${File.separator}sdcard${File.separator}idCardPic"
                        val file = File(pathname)
                        if (!file.exists()) {
                            file.mkdir()
                        }
                        picPath = "$pathname${File.separator}${idCardItem.certNumber}.jpg"
                        val fos = FileOutputStream(picPath)
                        compress = idCardItem.picBitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos)
                        fos.close()
                    }

                    val map = mutableMapOf<Any, Any>(
                            "method" to "receiveIDCardMsg",
                            "retCode" to idCardItem.retCode,
                            "partyName" to idCardItem.partyName,
                            "gender" to idCardItem.gender,
                            "nation" to idCardItem.nation,
                            "bornDay" to idCardItem.bornDay,
                            "certAddress" to idCardItem.certAddress,
                            "certNumber" to idCardItem.certNumber,
                            "certOrg" to idCardItem.certOrg,
                            "effDate" to idCardItem.effDate,
                            "expDate" to idCardItem.expDate,
                            "compress" to compress,
                            "picPath" to picPath,
                    )
                    bluetoothPlatform?.send(map)
                }
                BLUETOOTH_SOCKET_NOT_CONNECT -> {
                    bluetoothPlatform?.send("BluetoothSocket 未连接")
                }
                CONNECT_STATE -> {
                    val obj = msg.obj
                    val map = mutableMapOf<Any, Any>("method" to "connectState", "connectState" to obj)
                    bluetoothPlatform?.send(map)
                }
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()

//        unregisterReceiver(broadcast)
        BtReadClient.getInstance().disconnectBt()
    }


}

